package com.hrd.common.util.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 在java中处理http请求.
 *
 * @author nagsh
 *
 */
@Slf4j
public class HttpDeal {
	/**
	 * 处理get请求.
	 *
	 * @param url
	 *            请求路径
	 * @return json
	 */
	public static String get(String url) {

		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
				.setConnectionRequestTimeout(50000).setStaleConnectionCheckEnabled(true).build();

		// 实例化httpclient
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

		// 实例化get方法
		HttpGet httpget = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
		httpget.setConfig(requestConfig);
		// 请求结果
		CloseableHttpResponse response = null;
		String content = "";
		try {
			// 执行get方法
			response = httpclient.execute(httpget);
			if (response.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * 处理post请求.
	 *
	 * @param url
	 *            请求路径
	 * @param params
	 *            参数
	 * @return json
	 */
	public String post(String url, Map<String, String> params) {
		// 实例化httpClient
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 实例化post方法
		HttpPost httpPost = new HttpPost(url);
		// 处理参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}
		// 结果
		CloseableHttpResponse response = null;
		String content = "";
		try {
			// 提交的参数
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
			// 将参数给post方法
			httpPost.setEntity(uefEntity);
			// 执行post方法
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(response.getEntity(), "utf-8");
				System.out.println(content);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	// 编码格式。发送编码格式统一用UTF-8
	private static final String ENCODING = "UTF-8";
	//请求超时时间,这个时间定义了socket读数据的超时时间，也就是连接到服务器之后到从服务器获取响应数据需要等待的时间,发生超时，会抛出SocketTimeoutException异常。
	private static final int SOCKET_TIME_OUT = 600000;
	//连接超时时间,这个时间定义了通过网络与服务器建立连接的超时时间，也就是取得了连接池中的某个连接之后到接通目标url的连接等待时间。发生超时，会抛出ConnectionTimeoutException异常
	private static final int CONNECT_TIME_OUT = 600000;

	/**
	 * 以post方式调用第三方接口
	 * @param url
	 * @param headers
	 * @param params
	 * @return
	 */
	public static String post(String url, Map<String,String> headers,Object params) {
		log.info("post url:" + url);
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse httpResponse = null;
		String result = "";
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			if (headers != null && headers.size() > 0) {
				log.info("headers:" + JSONObject.toJSONString(headers));
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
			httpPost.setConfig(requestConfig);
			if (params != null) {
				String paramsJSON = JSONObject.toJSONString(params);
				log.info("params:" + paramsJSON);
				StringEntity jsonEntity = new StringEntity(paramsJSON,"UTF-8");
				jsonEntity.setContentType("application/json");
				httpPost.setEntity(jsonEntity);
			}
			httpResponse = httpClient.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity();
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(entity, ENCODING);
			}
			log.info("status:" + httpResponse.getStatusLine().getStatusCode() + ";result:" + result);
		} catch (IOException e) {
			log.error("post error", e);
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					log.error("close httpResponse error", e);
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					log.error("close httpClient error", e);
				}
			}
		}
		return result;
	}

}
